package sk.stuba.fiit.pki.ws.service.impl;

import java.math.BigInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;

import sk.stuba.fiit.pki.service.PkiService;
import sk.stuba.fiit.pki.ws.schema.beans.CertificateRequest;
import sk.stuba.fiit.pki.ws.schema.beans.CertificateResponse;
import sk.stuba.fiit.pki.ws.service.CommUtil;
import sk.stuba.fiit.pki.ws.service.MarshallingCertificateService;

@Endpoint
public class CertificateEndpoint implements MarshallingCertificateService{

	@Autowired
	PkiService pkiService;
	
	@PayloadRoot(localPart=CERTIFICATE_REQUEST, namespace=NAMESPACE)
	public CertificateResponse getCertificate(CertificateRequest request) {
		CertificateResponse certificateResponse = new CertificateResponse();
		try{
			
			String issuer = request.getCertificatereq().getIssuer();
			BigInteger serialNumber = null;
			if(request.getCertificatereq().getSerialNumber() != null)
				serialNumber = new BigInteger(request.getCertificatereq().getSerialNumber());
			byte[] resp;
			if(serialNumber != null){
				resp = pkiService.getCertificaateBySerialNumber(serialNumber,issuer);
			}else{
				resp = pkiService.getCertificateBySubjectIssuer(issuer);
			}
			 certificateResponse.withCertificateresp(CommUtil.getInstance().codeBase64ByteToString(resp));
			 return certificateResponse;
		}catch(Exception e){
			e.printStackTrace();
		}
		return new CertificateResponse();
	}

}
